package main.request;

import java.io.File;
import java.io.IOException;

import utils.Debug;
import main.process.FtpRequest;

public class RequestCwd implements ProcessRequestInterface {
	private static class SingletonHolder
	{		
		/** Instance unique non préinitialisée */
		private final static RequestCwd instance = new RequestCwd();
	}

	public static RequestCwd getInstance()
	{
		return SingletonHolder.instance;
	}

	@Override
	public void processRequest(String[] request, FtpRequest ftp) throws IOException {
		Debug.debug(this.getClass().getName(), request, ftp.getDebug());

		if(!request[0].equals("CWD"))
		{
			next(request, ftp);
		}
		else 
		{
			if(request[1].startsWith("/"))
				ftp.setPathName(request[1]);	
			else{	
				if(ftp.getPathName().compareTo("/") == 0)
					ftp.setPathName(ftp.getPathName() + request[1]);
				else
					ftp.setPathName(ftp.getPathName() + "/" + request[1]);
			}
			if(ftp.getPathName().startsWith(ftp.getRoot())){
				if(new File(ftp.getPathName()).exists())
					ftp.write(250 + " CWD ok");
				else{
					ftp.setPathName(ftp.getRoot());
					ftp.write(550 + " directory not exist");
				}
			}
			else{
				ftp.setPathName(ftp.getRoot());
				ftp.write(550 + " access denied");
			}
		}

	}

	@Override
	public void next(String[] request, FtpRequest ftp) throws IOException {
		RequestList.getInstance().processRequest(request, ftp);

	}

}
